package main

import (
	"github.com/gorilla/websocket"
	"sync"
	"time"
	"global/core"
)

type Manager struct {
	mux 			sync.Mutex
	clients 		map[*websocket.Conn]*Client
	outSignal 		chan *websocket.Conn
	ticker 			*time.Ticker
}

// 管理客户端程序
func NewManager() *Manager {
	return &Manager{
		outSignal: 		make(chan *websocket.Conn),
		clients: 		make(map[*websocket.Conn]*Client),
		ticker: 		time.NewTicker(2 * time.Second),
	}
}

func (m *Manager) listening() {
	go func() {
		for {
			select {
			case conn := <-m.outSignal:
				m.RemoveClient(conn)
			case <-m.ticker.C:
			}
		}
	}()
}

// 获取客户端
func (m *Manager) Get(conn *websocket.Conn) *Client {
	m.mux.Lock()
	defer m.mux.Unlock()
	if client, ok := m.clients[conn]; ok {
		return client
	}
	return nil
}

// 删除
func (m *Manager) RemoveClient(conn *websocket.Conn) {
	m.mux.Lock()
	defer m.mux.Unlock()
	if _, ok := m.clients[conn]; ok {
		delete(m.clients, conn)
	}
}

// 注册
func (m *Manager) Register(route string,
	ctx *core.Context,
	hi HandlerInterface,
	conn *websocket.Conn) {

	m.mux.Lock()
	defer m.mux.Unlock()

	if _, ok := m.clients[conn]; ok {
		return
	}

	c := NewClient(route, m, hi, conn)
	c.Start(ctx)

	m.clients[conn] = c
}
